﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LEET.CommonInterfaces.Compilers;
using LEET.LEETCommon.Model;
using Tedds_Tool.Instructions.Actions;

namespace LEET.StandardModules.Instructions
{
    public abstract class Action : Instruction
    {
        protected string type;
        protected string element;
        private int index;

        public Action(string[] args)
            : base(args)
        {
            type = args[1].Trim();
            element = (args.Count() > 2) ? args[2].Trim() : "";
            element = element.Replace("\"", "\\\"");
            index = 0;
        }

        [Obsolete("This should now be replaced by RenderStaticCall", false)]
        protected override String RenderedMethodName(int i)
        {
            index = i;
            return "_" + i + "_ACTION" + "()";
        }

        
        [Obsolete("This should now be replaced by RenderStaticCall", false)]
        protected String MethodBody(String pattern, String action)
        {
            StringBuilder buf = new StringBuilder();
            buf.Append("                AutomationElement e = HierarchyFinder.GetElement(\"").Append(element).Append("\", Box.RootElement);\r\n");
            buf.Append("                ").Append("Object obj; ").Append(pattern).Append(" pattern;\r\n");
            buf.Append("                e.TryGetCurrentPattern(").Append(pattern).Append(".Pattern, out obj);\r\n");
            buf.Append("                pattern = obj as ").Append(pattern).Append(";\r\n");
            buf.Append("                if(pattern != null)\r\n");
            buf.Append("                    pattern.").Append(action).Append(";\r\n");

            if (action == "Close()") buf.Append("                return new AutomationActionResult(ScriptSignal.Closing);\r\n");   //A window is closing, don't try Preconditions/Actions
            else                     buf.Append("                return new AutomationActionResult();\r\n");  //Needed for yield return.  Perhaps the state should be returned instead?
            return buf.ToString();
        }

        public static Action apply(String[] args)
        {
            Action ret = null;
            String type = args[1].Trim();
            switch (type)
            {
                case "INVOKE": ret = new Invoke(args); break;
                case "SETVAL": ret = new SetVal(args); break;
                case "TOGGLE": ret = new Toggle(args); break;
                case "SELECT": ret = new Select(args); break;
                case "ROTATE": ret = new Rotate(args); break;
                case "RESIZE": ret = new Resize(args); break;
                case "MOVE": ret = new Move(args); break;
                case "CLOSE": ret = new Close(args); break;
            }

            if (ret == null) throw new Exception("Unrecognized Action");

            return ret;
        }
    }
}
